﻿using AutoMapper;
using MediatR;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;
using Yitter.IdGenerator;

namespace RearLivestock.Beginning.Api.Application.Command.PigHistorys
{
    /// <summary>
    /// 猪只历史添加Handler
    /// </summary>
    public class AddPigHistoryHandler : IRequestHandler<AddPigHistoryCommand, Result>
    {
        private readonly IMapper mapper;
        /// <summary>
        /// 猪只历史
        /// </summary>
        private readonly IBaseRepository<PigHistory> pigHistoryrepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<AddPigHistoryHandler> _logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="pigHistoryrepository"></param>
        /// <param name="logger"></param>
        public AddPigHistoryHandler(IMapper mapper, IBaseRepository<PigHistory> pigHistoryrepository, ILogger<AddPigHistoryHandler> logger)
        {
            this.mapper = mapper;
            this.pigHistoryrepository = pigHistoryrepository;
            _logger = logger;
        }
        /// <summary>
        /// 猪只历史
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(AddPigHistoryCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                var res = pigHistoryrepository.AddRange(request.pigHistories);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "猪只历史添加成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "猪只历史添加异常" + ex.Message;
                _logger.LogError("猪只历史添加异常" + ex.Message);
            }
            return result;
        }
    }
}
